﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using LEEAAttendanceControl.Web;
using LEEAAttendanceControl.General;
using LEEAAttendanceControl.Web.Services;

using System.ServiceModel.DomainServices.Client;
using System.ComponentModel.DataAnnotations;

namespace LEEAAttendanceControl.Views
{
    public partial class UserEdit : ChildWindow
    {
        LEEAContext context = new LEEAContext();

        List<ValidationSummaryItem> errors = new List<ValidationSummaryItem>();

        bool editMode = false;

        User user = new User();

        public UserEdit()
        {
            InitializeComponent();
        }

        public UserEdit(string title)
        {
            Title = title;

            InitializeComponent();
        }

        public void LoadData(int id)
        {
            context.Load(context.GetUserByIdQuery(id), OnUserLoadCompleted, null);
        }

        private void OnUserLoadCompleted(LoadOperation load)
        {
            int comID = 0;

            context.Load(context.GetUserRolesQuery()).Completed += (s, e) =>
                {
                    RoleBox.ItemsSource = context.Roles;

                    context.Load(context.GetCompaniesQuery()).Completed += (s1, e1) =>
                    {
                        CompanyBox.ItemsSource = context.Companies;

                        user = (User)load.Entities.FirstOrDefault();

                        if (user == null)
                        {
                            user = new User();

                            user.Active = true;

                            comID = context.Companies.FirstOrDefault().ID;

                            context.Users.Add(user);
                        }
                        else
                        {
                            editMode = true;

                            if (user.Role1.RoleName == "Administrator")
                            {
                                comID = context.Companies.FirstOrDefault().ID;
                            }
                            else
                            {
                                comID =user.CompanyID.HasValue?user.CompanyID.Value:No.Zero;
                            }
                        }

                        context.Load(context.GetDepartmentsByCompanyIdQuery(comID)).Completed += (s2, e2) =>
                        {
                            DepartmentBox.ItemsSource = context.Departments;

                            DataContext = user;

                            editMode = false;
                        };
                    };
                };
        }

        private void RoleBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            
            if ((int) RoleBox.SelectedValue == 0)
            {
                user.CompanyID = null;
                CompanyBox.IsEnabled = false;

                user.DepartmentID = null;
                DepartmentBox.IsEnabled = false;
            }
            else if ((int) RoleBox.SelectedValue == 2)
            {
                CompanyBox.IsEnabled = true;

                user.DepartmentID = null;
                DepartmentBox.IsEnabled = false;
            }
            else
            {
                CompanyBox.IsEnabled = true;

                DepartmentBox.IsEnabled = true;
            }
            
        }

        private void CompanyBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (CompanyBox.SelectedIndex >= 0 && !editMode)
            {
                FillDepartmentList((int)CompanyBox.SelectedValue);
            }
        }

        private void FillDepartmentList(int comID)
        {
            context.Load(context.GetDepartmentsByCompanyIdQuery(comID), OnDepartmentsLoadCompleted, null);
        }

        private void OnDepartmentsLoadCompleted(LoadOperation load)
        {
            DepartmentBox.ItemsSource = load.Entities;
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            errors.Clear();
            ErrorSummary.Errors.Clear();

            context.IsLoginTaken(user.Login, taken =>
                {
                    if (taken.Value > 0 && taken.Value != user.UserID)
                    {
                        var error = new ValidationSummaryItem("Login already taken", "Login"
                            , ValidationSummaryItemType.PropertyError, null, null);

                        errors.Add(error);
                    }

                    if ((int)RoleBox.SelectedValue == 2 || (int)RoleBox.SelectedValue == 3)
                    {
                        if (CompanyBox.SelectedIndex < 0)
                        {
                            var error = new ValidationSummaryItem("Company is Required", "Company"
                                    , ValidationSummaryItemType.PropertyError, null, null);

                            errors.Add(error);
                        }
                    }

                    if ((int)RoleBox.SelectedValue == 3)
                    {
                        if (DepartmentBox.SelectedIndex < 0)
                        {
                            var error = new ValidationSummaryItem("Department is Required", "Department"
                                    , ValidationSummaryItemType.PropertyError, null, null);

                            errors.Add(error);
                        }
                    }

                    if (errors.Count > 0)
                    {
                        foreach (ValidationSummaryItem item in errors)
                        {
                            ErrorSummary.Errors.Add(item);
                        }
                    }
                    else
                    {
                        context.SubmitChanges(OnChangesSubmitted, null);
                    }
                }
                , null);
        }

        private void OnChangesSubmitted(SubmitOperation so)
        {
            if (so.HasError)
            {
                so.MarkErrorAsHandled();
            }
            else
            {
                MessageBox.Show(ApplicationStrings.GeneralSave, ApplicationStrings.GeneralSave, MessageBoxButton.OK);
                this.Close();
            }
        }
    }
}

